#!/usr/bin/env bash

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

BUILD_DIR=$( cd -- "$SCRIPT_DIR/../build" &> /dev/null && pwd )
BIN_DIR="$BUILD_DIR"/bin

ETS_FILE="$1"
ABC_FILE="${ETS_FILE%.ets}.abc"
PA_FILE="${ETS_FILE%.ets}.pa"
AOT_FILE="${ETS_FILE%.ets}.an"
ENTRY_POINT="$( basename "${ABC_FILE%.abc}" ).ETSGLOBAL::main"
STDLIB_ABC="$BUILD_DIR"/plugins/ets/etsstdlib.abc

set +e

ARK_ARGS=() # ark options

POSITIONAL_ARGS=()

while [[ $# -gt 0 ]]; do
  case $1 in
    -i|--interpreter)
      ARK_ARGS+=("--log-debug=interpreter")
      shift
      ;;
    -a|--aot)
      AOT=1
      shift
      ;;
    -d|--disasm)
      DISASM=1
      shift
      ;;
    -*)
      echo "Unknown option $1"
      exit 1
      ;;
    *)
      POSITIONAL_ARGS+=("$1") # save positional arg
      shift # past argument
      ;;
  esac
done

set -- "${POSITIONAL_ARGS[@]}" # restore positional parameters

set -xe

function es2panda() {
  "$BIN_DIR"/es2panda \
    --arktsconfig="$BUILD_DIR"/tools/es2panda/generated/arktsconfig.json \
    --gen-stdlib=false \
    --extension=ets \
    --opt-level=0 \
    --output="$2" \
    "$1"
}

function ark_disasm() {
  "$BIN_DIR"/ark_disasm "$1" "$2"
}

function ark_aot() {
  "$BIN_DIR"/ark_aot \
    --gc-type=g1-gc \
    --load-runtimes=ets \
    --full-gc-bombing-frequency=0 \
    --compiler-check-final=true \
    --compiler-ignore-failures=false \
    --boot-panda-files="$STDLIB_ABC" \
    --paoc-output="$2" \
    --paoc-panda-files="$1"
}

function ark() {
  local ARGS=("${ARK_ARGS[@]}")
  if [[ -n $3 ]]; then
    ARGS+=(
      --enable-an:force
      --aot-files="$3"
    )
  fi
  "${BIN_DIR}"/ark \
    --load-runtimes=ets \
    --interpreter-type=cpp \
    --gc-type=g1-gc \
    --full-gc-bombing-frequency=0 \
    --compiler-enable-jit=false \
    --coroutine-impl=stackful \
    --coroutine-workers-count=0 \
    --boot-panda-files="$STDLIB_ABC" \
    "${ARGS[@]}" \
    "$1" "$2"
}

es2panda "$ETS_FILE" "$ABC_FILE"
ark_disasm "$ABC_FILE" "$PA_FILE"
ark "$ABC_FILE" "$ENTRY_POINT"

# if [[ ! -f "${STDLIB_ABC%.abc}.an" ]]; then
#   ark_aot "$STDLIB_ABC" "${STDLIB_ABC%.abc}.an"
# fi

# ark_aot "$ABC_FILE" "$AOT_FILE"
# ark "$ABC_FILE" "$ENTRY_POINT" "$AOT_FILE"

unlink "$ABC_FILE"
